import React, { useEffect, useRef, useState } from 'react'
import { Alert, AppState, Appearance, Button, Keyboard, PermissionsAndroid, Platform, PlatformColor, Share, StyleSheet, Text, TextInput, ToastAndroid, View, useWindowDimensions } from 'react-native'

/* 
- 1. Alert.alert   提供模态框
- 2. Appearance    模块提供了关于用户外观偏好的信息，例如他们喜欢的颜色方案（明亮或暗黑
- 3. AppState      应用当前是在前台还是在后台，在状态变化的时候通知
- 4. Keyboard      监听键盘
    - addListener()     监听键盘事件   
    - removeListener()  移除监听事件    
    - dismiss()         弹出的键盘收回去，同时使当前的文本框失去焦点
- 5. PanResponder  手势 （不写demo 太多了  文档：https://www.reactnative.cn/docs/0.72/panresponder）
- 6. Platform      查看平台
- 7. Share         分享平台
- 8. transform     平移、旋转、透明基本与css一致
- 9. BackHandler   监听返回事件  仅在android
- 10. ToastAndroid 轻提示        仅在android
- 11. useWindowDimensions   获取屏幕尺寸
- 12. Vibration             设备震动
*/


export default function ApiDemo() {

  // alert 的按钮
  const alertBtn: Array<Object> = [
    {
      text: "Cancel",
      onPress: () => console.log("Cancel Pressed"),
      style: "cancel"
    },
    { text: "OK", onPress: () => console.log("OK Pressed") }
  ]

  // alert的配置项
  const alertOption = {
    cancelable: true, // 点击蒙层关闭弹框
    onDismiss: () =>
      Alert.alert(
        "点击蒙层关闭弹框"
      ),
  }

  const createButtonAlert = () => {
    return Alert.alert(
      "Alert Title",
      "My Alert Msg",
      alertBtn,
      alertOption
    );
  }



  const createToast = () => {
    // show 方法 (message , 持续时间 SHORT/LONG )  不能指定位置
    // ToastAndroid.show("A pikachu appeared nearby !", ToastAndroid.SHORT );
    ToastAndroid.showWithGravity(
      'this is toast',
      ToastAndroid.SHORT,
      ToastAndroid.CENTER,
    )

  }


  const windowWidth = useWindowDimensions().width;
  const windowHeight = useWindowDimensions().height;
  const fontScale = useWindowDimensions().fontScale
  console.log(`windowWidth:${windowWidth}; windowHeight:${windowHeight};fontScale:${fontScale} `);



  // 查看主题色
  const colorScheme = Appearance.getColorScheme();
  console.log('颜色模式：', colorScheme);

  // 设置主题色
  const changetheme = () => {
    Appearance.setColorScheme('light')
  }


  // 查看是否在前台
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);
  // 要获取当前的状态，你可以使用AppState.currentState
  useEffect(() => {
    const subscription = AppState.addEventListener('change', nextAppState => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === 'active'
      ) {
        console.log('App has come to the foreground!');
      }
      appState.current = nextAppState;
      setAppStateVisible(appState.current);
      console.log('AppState', appState.current);
    });
    return () => {
      subscription.remove();
    };
  }, []);


  // 弹出的键盘收回去，同时使当前的文本框失去焦点
  const submit = () => {
    Keyboard.dismiss()
  }


  const onShare = async () => {
    const result = await Share.share({
      title: '分享标题',
      message: '分享的内容',
    });
    // 成功分享
    if (result.action === Share.sharedAction) {
      if (result.activityType) {
        // shared with activity type of result.activityType
      } else {
        // shared
      }
    } else if (result.action === Share.dismissedAction) {
      // 分享失败
    }
  };



  const onPermission = async () => {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_CALENDAR, // 要请求的权限
      // 提示弹框
      {
        title: "Cool Photo App Camera Permission",
        message:
          "Cool Photo App needs access to your camera " +
          "so you can take awesome pictures.",
        buttonNeutral: "Ask Me Later",
        buttonNegative: "Cancel",
        buttonPositive: "OK"
      }
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use the camera");
    } else {
      console.log("Camera permission denied");
    }
  }





  const needPermission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
  // PermissionsAndroid.check(
  //   needPermission
  // ).then(result => {
  //   if (!result) {
  //     PermissionsAndroid.request(needPermission).then(status => {
  //       console.log(status);
  //       if (status === 'granted') {
  //         //获得
  //       } else if (status === 'denied') {
  //         //拒绝
  //       }
  //     });
  //   }
  // });

  // PermissionsAndroid.requestMultiple([
  //   PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
  //   PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
  // ]);





  return (
    <View style={styles.container} >
      <View style={styles.btn}>
        <Button title={"show alert"} onPress={createButtonAlert} />
      </View>
      <View style={styles.btn}>
        <Button title={"show Toast"} onPress={createToast} />
      </View>
      <View style={styles.btn}>
        <Button title={"change theme"} onPress={changetheme} />
      </View>
      
      <View style={styles.btn}>
        <Button onPress={onShare} title="Share" />
      </View>
      <View style={styles.btn}>
        <Button onPress={onPermission} title="Permission" />
      </View>
      <View style={styles.btn}>
        <TextInput
          style={styles.input}
          placeholder="click here"
          onSubmitEditing={submit} // 点击提交事件
        />
      </View>
      <View style={styles.btn}>
        <Text style={styles.text}>{appStateVisible} </Text>
      </View>
      
      <Text style={styles.text}>{`OS:${Platform.OS}`}</Text>
      <Text style={styles.text}>{`OS Version:${Platform.Version}`}</Text>


      <View
        style={[
          styles.box,
          {
            transform: [{ scale: 2 }, { rotate: '45deg' }, { translateX: 10 }, { skewX: '40deg' }],
          },
        ]}>
        <Text style={styles.text}>Scale by </Text>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center"
  },
  btn: {
    marginVertical: 10
  },
  text: {
    fontSize: 10,
    marginVertical: 10
  },
  input: {
    margin: 10,
    padding: 10,
    borderWidth: 0.5,
    borderRadius: 4,
    backgroundColor: "#fff"
  },
  box: {
    height: 40,
    width: 40,
    borderRadius: 5,
    marginVertical: 40,
    backgroundColor: '#61dafb',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
